package com.chatplus.application.aiprocessor.function.impl;

import com.chatplus.application.aiprocessor.function.TriggerFunctionService;
import com.chatplus.application.aiprocessor.provider.TriggerFunctionServiceProvider;
import com.chatplus.application.common.domain.response.TurnRightResponse;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.extend.ZaoBaoNewsDto;
import com.chatplus.application.domain.entity.functions.FunctionEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;

/**
 * 新闻
 */
@Service(value = TriggerFunctionServiceProvider.SERVICE_NAME_PRE + ZaoBaoServiceImpl.NEWS)
public class ZaoBaoServiceImpl extends TriggerFunctionService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ZaoBaoServiceImpl.class);

    public static final String NEWS = "zaobao";
    private final ObjectMapper objectMapper;

    public ZaoBaoServiceImpl(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public String executeReturnMarkdown(FunctionEntity functionEntity, String arguments) {
        String result = "";
        try {
            result = commonExecute(functionEntity, arguments);
            LOGGER.message("今日早报结果").context("result", result).info();
            TurnRightResponse turnRightResponse = objectMapper.readValue(result, TurnRightResponse.class);
            if (Objects.equals(turnRightResponse.getCode(), TurnRightResponse.SUCCESS)
                    && Objects.nonNull(turnRightResponse.getData())) {
                ZaoBaoNewsDto zaoBaoNewsDto =
                        objectMapper.readValue(objectMapper.writeValueAsString(turnRightResponse.getData()), ZaoBaoNewsDto.class);
                StringBuilder stringBuilder = new StringBuilder();
                List<String> news = zaoBaoNewsDto.getNews();
                String weiYu = zaoBaoNewsDto.getWeiYu();
                for (String newStr : news) {
                    stringBuilder.append(newStr)
                            .append("<br/><br/>");
                }
                if (StringUtils.isNotEmpty(weiYu)) {
                    stringBuilder.append(weiYu);
                }
                return stringBuilder.toString();
            }
        } catch (Exception e) {
            LOGGER.message("今日早报结果报错").context("result", result).exception(e).error();
        }
        return "今日早报结果异常，等待管理员处理";
    }

    @Override
    public String getFunctionChannel() {
        return NEWS;
    }
}
